package studiodiva.portfolio.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class CrawlerFilter implements Filter {

  private final String snapshootService = "http://diva-ajax-crawler.appspot.com/";

  public void destroy() {}

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (isCrawlerRequest(httpRequest.getQueryString()))
      returnCrawlableResponse(response, httpRequest);
    else chain.doFilter(request, response);
  }

  public void init(FilterConfig filterConfig) throws ServletException {}

  private String createRequestUrl(HttpServletRequest request) {
    String reqUrl = request.getRequestURL().toString();
    String queryString = request.getQueryString();
    if (queryString != null) reqUrl += "?" + queryString;
    return reqUrl;
  }

  private boolean isCrawlerRequest(String query) {
    return query != null && query.contains("_escaped_fragment_=");
  }

  private void returnCrawlableResponse(ServletResponse response, HttpServletRequest request)
      throws IOException, MalformedURLException, UnsupportedEncodingException {
    System.out
        .println("returnCrawlableResponse(ServletResponse response, HttpServletRequest request)");
    String reqUrl = URLEncoder.encode(createRequestUrl(request), "UTF-8");

    response.setContentType("text/html");
    response.setCharacterEncoding("ISO-8859-1");
    ServletOutputStream out = response.getOutputStream();
    try {
      URL url = new URL(snapshootService + "/ajaxcrawler?url=" + reqUrl);
      BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
      String line;
      while ((line = reader.readLine()) != null)
        writer.write(line);
      reader.close();
      writer.close();
    } catch (Exception e) {
      out.print("<html><head></head><body>" + e.getMessage() + "</body></html>");
    }
  }
}
